<?php

namespace app\common\service\logistics;

use app\common\library\ApiException;
use app\common\library\Auth;
use app\common\library\Wxapp;
use app\common\model\Third;
use app\common\model\User as UserMd;
use app\common\model\UserAuth;
use think\Db;
use think\Exception;
use think\Request;

class User
{
    /**
     * 授权登录
     * @param Request $request
     * @return array
     * @throws ApiException
     */
    public function auth_login(Request $request)
    {
        $request->filter(['strip_tags']);
        $code = $request->param("code");
        if(!$code){
            throw new ApiException("参数错误");
        }
        $nickname = $request->param("nickname","微信用户");
        $avatar   = $request->param("avatar");
        $code = trim($code);
        $wx_pay = new Wxapp();
        Db::startTrans();
        try {
            $res = $wx_pay->AuthLogin($code);
            $auth = new Auth();
            $third = Third::where("openid",$res["openid"])->find();
            if($third){
                $third->save([
                    "access_token" => $res["session_key"],
                    "logintime"   => time(),
                ]);
                $auth->direct($third->user_id);
                Db::commit();
                return $auth->getUserinfo();
            }else{
                 $res1 = $auth->register("",[
                     "avatar"   => $avatar,
                     "nickname" => $nickname,
                 ]);
                 if($res1){
                     Third::create([
                         "openid"        => $res["openid"],
                         "access_token"  => $res["session_key"],
                         "logintime"     => time(),
                         "user_id"       => $auth->id,
                         "openname"      => $nickname
                     ]);
                     Db::commit();
                     return $auth->getUserinfo();
                 }else{
                     throw new Exception("登录授权失败");
                 }
            }
        } catch (ApiException $e) {
            Db::rollback();
            throw new ApiException($e->getMessage());
        }

    }


    /**
     * 编辑用户资料
     * @param $uid
     * @param Request $request
     * @return true
     * @throws ApiException
     */
    public function user_edit($uid,Request $request)
    {
        $request->filter(['strip_tags']);
        Db::startTrans();
        try {
            $upd_data = [];
            $avatar = $request->param("avatar");
            if($avatar){
                $upd_data["avatar"] = $avatar;
            }
            $nickname = $request->param("nickname");
            if($nickname){
                $upd_data["nickname"] = $nickname;
            }
            $mobile   = $request->param("mobile");
            if($mobile){
                if(UserMd::getByMobile($mobile)){
                    throw new ApiException("手机号已存在!");
                }
                $upd_data["mobile"] = $mobile;
            }
            $res = UserMd::where("id",$uid)->update($upd_data);

            Db::commit();
            return true;
        }catch (Exception $e){
            Db::rollback();
            throw new ApiException($e->getMessage());
        }
    }

    public function user_info($uid)
    {
        return UserMd::where('id',$uid)->field("id,auth_type,express_type,nickname,mobile,avatar")
            ->find();
    }


    public function auth_mobile($uid,Request $request)
    {
        $request->filter(['strip_tags']);
        $code=  $request->param('code');
        if(!$code){
            throw new ApiException("获取参数错误");
        }
        $wx_pay = new Wxapp();
        return $wx_pay->AuthMobile($uid,$code);

    }


    /**
     * 实名信息
     * @param $uid
     */
    public function real_info($uid)
    {
        return UserAuth::where("user_id",$uid)->find();
    }

    /**
     * 实名认证
     * @param $uid
     * @param Request $request
     * @return true
     * @throws ApiException
     */
    public function auth_user($auth,Request $request)
    {
        $request->filter(['strip_tags']);
        if($auth->auth_type == 1){
            throw new ApiException("您已经实名认证");
        }
        $username = $request->param("username");
        $gender   = $request->param("gender");
        $id_no    = $request->param("id_no");
        $cart_img1= $request->param("cart_img1");
        $cart_img2= $request->param("cart_img2");
        if(!$username || !$gender || !$id_no || !$cart_img2 || !$cart_img1){
            throw new ApiException("输入的信息不完整");
        }
        Db::startTrans();
        try {
            $u_res = UserAuth::where("user_id",$auth->id)->count();
            if($u_res){
                throw new ApiException("实名信息已存在");
            }
            $res = UserAuth::create([
                "user_id"   => $auth->id,
                "username"  => trim($username),
                "gender"    => $gender,
                "id_no"     => trim($id_no),
                "cart_img1" => $cart_img1,
                "cart_img2" => $cart_img2,
                "status"    => 1
            ]);
            if(!$res){
                throw new ApiException("添加实名失败");
            }
            UserMd::where("id",$auth->id)->update(["auth_type"=>1]);
            Db::commit();
            return true;
        }catch (Exception $e){
            Db::rollback();
            throw new ApiException($e->getMessage());
        }
    }

}